import actionTypes from './constants';
import {loginRequest} from '../../services';


//同步
//开始登录
const startLogin = () => {
    return {
        type: actionTypes.START_LOGIN
    }
}
//登录成功
const loginSuccess = (userInfo) => {
    return {
        type: actionTypes.LOAGIN_SUCCESS,
        payLoad: {
            userInfo
        }
    }
}
//登录失败处理
const loginFailed = () => {
    //清除本地记录
    window.localStorage.removeItem('authToken');
    window.sessionStorage.removeItem('authToken');
    window.localStorage.removeItem('userInfo');
    window.sessionStorage.removeItem('userInfo');
    return {
        type: actionTypes.LOGIN_FAILED
    }
}

//登录
export const login= (userInfo) => {
    // console.log(userInfo);
    return dispatch => {
        dispatch(startLogin);
        loginRequest(userInfo)
        .then(res => {
            // console.log(res);
            //返回的状态码为200的时候表示登录成功
            if(res.data.code === 200){
                //在这里需要做本地化存储
                const {authToken, ...userInfo} = res.data.data;
                if(userInfo.remember === true){
                    window.localStorage.setItem('authToken', authToken);
                    window.localStorage.setItem('userInfo', JSON.stringify(userInfo));
                    
                }else {
                    window.sessionStorage.setItem('authToken', authToken);
                    window.sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
                }
                dispatch(loginSuccess({
                    ...res.data.data
                }))
            }else {
                dispatch(loginFailed());
            }
        })
        
    }
}

//登录失败
// export const logout = () => {
//     //实际的项目中需要告诉服务端用户已经退出
//     return dispatch => {
//         dispatch(loginFailed);

//     }
// }

//退出登录测试
export const logout = () => {
    //实际的项目中需要告诉服务端用户已经退出
    // console.log('正在执行退出');
    window.localStorage.removeItem('authToken');
    window.sessionStorage.removeItem('authToken');
    window.localStorage.removeItem('userInfo');
    window.sessionStorage.removeItem('userInfo');
    return {
        type: actionTypes.LOGOUT
    }
}


//上传头像
export const changeAvatar = (avatarUrl) => {
    // console.log(avatarUrl);
    return {
        type: actionTypes.CHANGEAVATAR,
        payLoad: {
            avatarUrl
        }
    }
}